﻿using DGZImp.Core.Utilities;
using DGZImp.MdsProject.Base;
using DGZImp.MdsProject.Devices.Base;
using DGZImp.MdsProject.Devices.Helper;
using DGZImp.MdsProject.Devices.Models;
using DGZImp.MdsProject.Helper;
using DGZImp.MdsProject.Services;
using Microsoft.Extensions.DependencyInjection;
using Nomad.Iot;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DGZImp.MdsProject.Devices
{
    /// <summary>
    /// 提升机
    /// </summary>
    public class Hoister : PlcDevice<HoisterData>
    {
        public Hoister(string id, string name, IIotServe serve, List<PlcDataMapItem> maps) : base(id, name, serve, maps)
        {
            OnDataChange += HoisterOnDataChange;
        }

        public async void HoisterOnDataChange(object sender)
        {
            if (Data.EventCode == HoistEventEnum.已完成 && Data.TaskNo != 0)
            {
                var service = ServiceProviderAccessor.ServiceProvider.GetService<Mds_LogisticTaskService>();
                await service.FinishLogisticDetailTask(null, Data.TaskNo);
                await ClearTaskAsync();
            }
        }

        public async Task<OperateResult> SendNormalTaskAsync([MdsParameter("任务号")] int taskNo, [MdsParameter("起始点")] int start, [MdsParameter("目标点")] int end)
        {
            if (Data.Status != HoistStatusEmun.空闲)
                return new OperateResult { IsSuccess = false, Message = $"{Name}不是空闲状态" };

            if (Data.WorkingLock != 0)
                return new OperateResult { IsSuccess = false, Message = $"{Name}处于对接锁定状态" };

            return await WriteDataToPlc(new List<PlcDataWriteItem> {
                new(){ PropName = nameof(HoisterData.Command), Value = HoistCommandEmun.新任务 },
                new(){ PropName = nameof(HoisterData.WriteStart), Value = start },
                new(){ PropName = nameof(HoisterData.WriteEnd), Value = end },
                new(){ PropName = nameof(HoisterData.WriteTaskNo), Value = taskNo },
            });
        }

        [MdsAction("新任务", "发送一个提升机任务")]
        public async Task<OperateResult> SendTaskAsync([MdsParameter("起始点")] int start, [MdsParameter("目标点")] int end)
        {
            var taskNo = SimpleSnowId.GenerateId();
            return await SendNormalTaskAsync(taskNo, start, end);
        }

        [MdsAction("清除任务", "清除提升机任务")]
        public async Task<OperateResult> ClearTaskAsync()
        {
            if (Data.Status != HoistStatusEmun.空闲 && Data.Status != HoistStatusEmun.运行中)
                return new OperateResult { IsSuccess = false, Message = $"{Name}不是联机状态" };

            return await WriteDataToPlc(new List<PlcDataWriteItem> {
                new(){ PropName = nameof(HoisterData.Command), Value = HoistCommandEmun.清除任务 },
                new(){ PropName = nameof(HoisterData.WriteStart), Value = 0 },
                new(){ PropName = nameof(HoisterData.WriteEnd), Value = 0 },
                new(){ PropName = nameof(HoisterData.WriteTaskNo), Value = 0 },
            });
        }

        [MdsAction("设备对接锁定", "发送一个设备对接信号，让提升机短暂锁定")]
        public async Task<OperateResult> SendWorkingLockAsync()
        {
            if (Data.Status != HoistStatusEmun.空闲)
                return new OperateResult { IsSuccess = false, Message = $"{Name}非空闲，不应下发锁定信号" };
            return await WriteDataToPlc(new List<PlcDataWriteItem> {
                new(){ PropName = nameof(HoisterData.WorkingLock), Value = 1 }
            });
        }

        [MdsAction("设备对接解锁", "发送一个设备对接完成信号，让提升机解除锁定")]
        public async Task<OperateResult> SendWorkingUnlockAsync()
        {
            if (Data.Status != HoistStatusEmun.空闲)
                return new OperateResult { IsSuccess = false, Message = $"{Name}非空闲，不应下发解锁信号" };
            return await WriteDataToPlc(new List<PlcDataWriteItem> {
                new(){ PropName = nameof(HoisterData.WorkingLock), Value = 0 }
            });
        }
    }

    public class HoisterData
    {
        [Description("01.心跳")]
        public int Heartbeat { get; set; }

        [Description("02.状态")]
        public HoistStatusEmun Status { get; set; }

        [Description("03.事件")]
        public HoistEventEnum EventCode { get; set; }

        [Description("04.有货无货")]
        public GoodsStatusEnum IsFull { get; set; }

        [Description("05.当前位置")]
        public int CurPos { get; set; }

        [Description("06.当前任务号")]
        public int TaskNo { get; set; }

        [Description("07.任务起点")]
        public int Start { get; set; }

        [Description("08.任务终点")]
        public int End { get; set; }

        [Description("09.错误码")]
        public int Error { get; set; }


        [Description("80.写入指令")]
        public HoistCommandEmun Command { get; set; }

        [Description("81.写入任务号")]
        public int WriteTaskNo { get; set; }

        [Description("82.写入起点")]
        public int WriteStart { get; set; }

        [Description("83.写入终点")]
        public int WriteEnd { get; set; }
        /// <summary>
        /// 1.锁定 2.解锁
        /// </summary>
        [Description("84.设备对接锁定")]
        public int WorkingLock { get; set; }

        [Description("99.刷新时间")]
        public string RefreshTime { get; set; }

    }
}
